import axios from "axios";
import { getData, getSettings, saveSettings } from "./db";
import utils from "./utils";
import dayjs from "dayjs";

interface BinanceResponse {
  data: {
    symbol: string;
    pair: string;
    contractType: string;
    deliveryDate: number;
    onboardDate: number;
  };
}

export async function binanceJob() {
  console.log('binance job ' + dayjs().format('MM-DD HH:mm:ss'))
  const { data: response } = await axios.get<BinanceResponse>('https://maneki.cc/api/binance/lastcoin');
  const lastSymbol = await getSettings("", 'binance_last_symbol') || '';
  const lastCoin = response;

  if (lastCoin.symbol !== lastSymbol) {
    await saveSettings("", 'binance_last_symbol', lastCoin.symbol);
    
    const data = await getData();
    const chats = Object.entries(data.settings)
      .filter(([key, value]) => key.startsWith('binance_status_') && value)
      .map(([key]) => key.replace('binance_status_', ''));

    for (const chat of chats) {
      await utils.sendMessage(chat, `币安新币: ${lastCoin.symbol}\n交易对: ${lastCoin.pair}\n上线时间: ${dayjs(lastCoin.onboardDate).format("YYYY-MM-DD HH:mm")}`);
    }
  }
}